<template>
  <view class="page-container">
    <!-- 自定义顶部标题栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="goBack">
        <icon type="back" size="23" color="#333"></icon>
      </view>
      <view class="navbar-title">
        <icon type="success" size="25" color="orange"></icon>
      </view>
      <view class="navbar-right"></view>
    </view>

    <!-- 卡片式布局 -->
    <view class="content-container">
      <!-- 标题区域 -->
      <view class="page-title">
        <text>考勤打卡</text>
      </view>
      
      <!-- 图片上传区域 -->
      <view class="upload-section">
        <view class="upload-circle" @click="triggerUpload">
          <icon type="camera" size="40" color="#2979ff"></icon>
          <text>点击上传打卡图片</text>
        </view>
      </view>

      <!-- 已上传图片展示区域 -->
      <view class="card-container upload-card" v-if="fileList.length > 0">
        <view class="card-header">
          <view class="header-with-icon">
            <icon type="success" size="20" color="#2979ff"></icon>
            <text>已上传图片</text>
          </view>
        </view>
        <view class="upload-content">
          <swiper class="preview-swiper" :indicator-dots="true" indicator-color="rgba(0, 0, 0, .3)" indicator-active-color="#2979ff">
            <swiper-item v-for="(item, index) in fileList" :key="index" class="swiper-item">
              <view class="preview-item">
                <image :src="item.content" @click="previewImage(item)" mode="aspectFill"></image>
                <view class="close-circle" @click.stop="removeImage(index)">
                  <icon type="cancel" size="16" color="#fff"></icon>
                </view>
              </view>
            </swiper-item>
          </swiper>
          <view class="hidden-uploader" @click="triggerUpload"></view>
        </view>
      </view>

      <!-- 打卡信息区域 -->
      <view v-if="recordInfo" class="card-container info-card">
        <view class="card-header">
          <text>打卡信息</text>
          <view class="edit-icon" @click="toggleEdit">
            <icon :type="isEditing ? 'success' : 'info'" size="22" color="#FF9800"></icon>
          </view>
        </view>
        <view class="info-content">
          <!-- 用户姓名 -->
          <view class="info-item">
            <view class="info-label">
              <icon type="success" size="18" color="#2979ff"></icon>
              <text>用户姓名</text>
            </view>
            <view class="info-value">
              <template v-if="isEditing">
                <input
                    v-model="editedInfo.username"
                    :placeholder="recordInfo.username"
                    class="edit-field"
                />
              </template>
              <template v-else>
                <text class="highlight-text">{{ recordInfo.username }}</text>
              </template>
            </view>
          </view>
          
          <!-- 打卡日期 -->
          <view class="info-item">
            <view class="info-label">
              <icon type="waiting" size="18" color="#2979ff"></icon>
              <text>打卡日期</text>
            </view>
            <view class="info-value">
              <template v-if="isEditing">
                <input
                    v-model="editedInfo.today"
                    :placeholder="recordInfo.today"
                    class="edit-field"
                />
              </template>
              <template v-else>
                <text>{{ recordInfo.today }}</text>
              </template>
            </view>
          </view>
          
          <!-- 打卡时段 -->
          <view class="time-group">
            <view class="time-header">
              <icon type="waiting" size="18" color="#2979ff"></icon>
              <text>打卡时段</text>
            </view>
            
            <!-- 上班时间 -->
            <view class="info-item time-item">
              <view class="info-label time-label">
                <text>上班时间</text>
              </view>
              <view class="info-value">
                <template v-if="isEditing">
                  <input
                      v-model="editedInfo.firstRecord"
                      :placeholder="recordInfo.firstRecord"
                      class="edit-field"
                  />
                </template>
                <template v-else>
                  <text>{{ recordInfo.firstRecord }}</text>
                </template>
              </view>
            </view>
            
            <!-- 下班时间 -->
            <view class="info-item time-item">
              <view class="info-label time-label">
                <text>下班时间</text>
              </view>
              <view class="info-value">
                <template v-if="isEditing">
                  <input
                      v-model="editedInfo.endRecord"
                      :placeholder="recordInfo.endRecord"
                      class="edit-field"
                  />
                </template>
                <template v-else>
                  <text>{{ recordInfo.endRecord }}</text>
                </template>
              </view>
            </view>
          </view>
        </view>
        
        <view class="action-buttons">
          <button 
              class="submit-btn"
              :class="{'loading': isSubmitting}"
              :disabled="isSubmitting"
              @click="submitRecord"
          >
            {{isSubmitting ? '提交中...' : '确认'}}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config';

export default {
  data() {
    return {
      fileList: [],
      isEditing: false,
      isSubmitting: false,
      recordInfo: null,
      editedInfo: {
        username: '',
        today: '',
        firstRecord: '',
        endRecord: ''
      }
    };
  },
  onLoad() {
    // 检查登录状态
    const token = uni.getStorageSync('App-Token');
    if (!token) {
      uni.navigateTo({
        url: '/pages/login/index'
      });
      return;
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    triggerUpload() {
      // 触发上传文件选择
      uni.chooseImage({
        count: 1, // 限制只选择一张图片
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 处理选择的图片
          const tempFilePaths = res.tempFilePaths;
          const tempFiles = res.tempFiles;
          
          if (tempFilePaths.length > 0) {
            // 添加到现有图片列表
            this.fileList = [
              ...this.fileList, 
              {
                url: tempFilePaths[0],
                content: tempFilePaths[0],
                file: {
                  size: tempFiles[0].size
                }
              }
            ];
            
            // 直接传递文件路径给processImage
            this.processImage(tempFilePaths[0]);
          }
        }
      });
    },
    processImage(fileObj) {
      const token = uni.getStorageSync('App-Token');
      if (!token) {
        uni.showToast({
          title: '未登录，请先登录',
          icon: 'none'
        });
        return;
      }

      const finalToken = token.startsWith('Bearer ') ? token : 'Bearer ' + token;

      uni.showLoading({
        title: '识别中...'
      });

      uni.uploadFile({
        url: config.baseUrl + '/kq/upload/photo',
        filePath: fileObj.path || fileObj,
        name: 'file',
        header: {
          'Authorization': finalToken
        },
        success: (uploadFileRes) => {
          uni.hideLoading();
          
          // 解析返回数据
          const res = JSON.parse(uploadFileRes.data);
          
          if (res.code === 200) {
            this.recordInfo = res.data;
            
            // 复制到编辑表单
            this.editedInfo = {...this.recordInfo};
            
            uni.showToast({
              title: '识别成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: res.msg || '识别失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          uni.hideLoading();
          uni.showToast({
            title: '识别失败: ' + JSON.stringify(error),
            icon: 'none'
          });
        }
      });
    },
    previewImage(item) {
      uni.previewImage({
        urls: [item.content],
        current: item.content
      });
    },
    removeImage(index) {
      this.fileList.splice(index, 1);
      // 清除识别结果
      this.recordInfo = null;
    },
    toggleEdit() {
      if (this.isEditing) {
        // 保存编辑
        this.recordInfo = {...this.editedInfo};
        this.isEditing = false;
        
        uni.showToast({
          title: '已保存修改',
          icon: 'success'
        });
      } else {
        // 开始编辑
        this.isEditing = true;
        
        uni.showToast({
          title: '您可以编辑打卡信息',
          icon: 'none'
        });
      }
    },
    submitRecord() {
      const token = uni.getStorageSync('App-Token');
      if (!token) {
        uni.showToast({
          title: '未登录，请先登录',
          icon: 'none'
        });
        return;
      }

      const finalToken = token.startsWith('Bearer ') ? token : 'Bearer ' + token;

      if (!this.recordInfo) {
        uni.showToast({
          title: '请先上传打卡图片',
          icon: 'none'
        });
        return;
      }

      this.isSubmitting = true;

      this.recordInfo.userId = this.$store.getters.userId;

      uni.request({
        url: config.baseUrl + '/kq/record/submit',
        method: 'POST',
        data: this.recordInfo,
        header: {
          'Content-Type': 'application/json',
          'Authorization': finalToken
        },
        success: (res) => {
          this.isSubmitting = false;
          
          if (res.data.code === 200) {
            uni.showToast({
              title: '提交成功',
              icon: 'success'
            });
            
            // 提交成功后返回
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res.data.msg || '提交失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          this.isSubmitting = false;
          uni.showToast({
            title: '提交失败: ' + JSON.stringify(error),
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 40px;
}

/* 自定义导航栏样式 */
.custom-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #fff;
  position: relative;
  height: 44px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
}

.navbar-left, .navbar-right {
  width: 60px;
  display: flex;
  align-items: center;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-weight: bold;
  display: flex;
  justify-content: center;
}

.content-container {
  padding: 15px;
  padding-top: 20px;
}

.page-title {
  text-align: center;
  margin-bottom: 20px;
  
  text {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}

.upload-section {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  margin-top: 5px;
}

.upload-circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
  text {
    margin-top: 10px;
    font-size: 12px;
    color: #999;
  }
}

.card-container {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 15px;
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f2f2f2;
  
  text {
    font-size: 15px;
    font-weight: bold;
  }
  
  .edit-icon {
    color: #FF9800;
  }
}

.upload-card {
  .upload-content {
    padding: 10px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 140px;
    position: relative;
    width: 100%;
  }
}

.preview-swiper {
  width: 100%;
  height: 120px;
}

.swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  padding: 0 15px;
}

.preview-item {
  position: relative;
  width: 100%;
  height: 120px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  overflow: hidden;

  image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }

  .close-circle {
    position: absolute;
    top: 6px;
    right: 6px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
  }
}

.header-with-icon {
  display: flex;
  align-items: center;
}

.hidden-uploader {
  display: none;
}

.info-card {
  .info-content {
    padding: 0 15px;
  }
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f2f2f2;
  
  &:last-child {
    border-bottom: none;
  }
}

.info-label {
  display: flex;
  align-items: center;
  
  text {
    margin-left: 5px;
    font-size: 14px;
    color: #333;
  }
}

.info-value {
  flex: 1;
  text-align: right;
  font-size: 14px;
  color: #666;
  padding-left: 10px;
}

.time-group {
  margin-top: 5px;
  padding-bottom: 15px;

  .time-header {
    display: flex;
    align-items: center;
    padding: 12px 0;
    
    text {
      margin-left: 5px;
      font-size: 14px;
      color: #333;
    }
  }
  
  .time-item {
    padding-left: 20px;
  }
  
  .time-label {
    text {
      color: #666;
    }
  }
}

.highlight-text {
  color: #2979ff;
  font-weight: bold;
}

.edit-field {
  text-align: right;
  background-color: #f8f8f8;
  border-radius: 4px;
  padding-right: 8px;
  padding: 5px 8px;
  height: 30px;
  border: none;
  width: 100%;
  font-size: 14px;
  color: #333;
}

.action-buttons {
  padding: 15px;
  border-top: 1px solid #f2f2f2;
  
  .submit-btn {
    width: 100%;
    height: 45px;
    line-height: 45px;
    border-radius: 30px !important;
    box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
    background-color: #2196F3;
    color: #fff;
    font-size: 16px;
    border: none;
    
    &.loading {
      opacity: 0.8;
    }
  }
}
</style>

